use std::fs;

use casbin::{CoreApi, FileAdapter};
use serde::Deserialize;

#[derive(Clone, Deserialize, Debug)]
pub struct CasbinConfig {
    model: String,
    policy: String,
}

impl CasbinConfig {
    pub fn is_db(&self) -> bool {
        self.policy.starts_with("mysql")
            || self.policy.starts_with("sqlite")
            || self.policy.starts_with("postgres")
    }

    pub async fn casbin(self) -> Result<casbin::prelude::Enforcer, casbin::Error> {
        let model_str = fs::read_to_string(&self.model).unwrap();
        let m = casbin::DefaultModel::from_str(&model_str).await.unwrap();
        Ok(if self.is_db() {
            let a = seaorm_adapter::SeaOrmAdapter::new(&self.policy)
                .await
                .unwrap();
            casbin::Enforcer::new(m, a).await.unwrap()
        } else {
            casbin::Enforcer::new(m, FileAdapter::new(self.policy))
                .await
                .unwrap()
        })
    }
}
